package com.haierp.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Sets;
import com.haierp.dto.MultiDeliveryFormDTO;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.ShippingOrderStatus;
import com.haierp.enums.StockUpStatus;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.ErpOrderMapper;
import com.haierp.mapper.LogisticCompanyMapper;
import com.haierp.mapper.LogisticTypeMapper;
import com.haierp.mapper.ShippingOrderMapper;
import com.haierp.mapper.ShippingTrackMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.LogisticCompany;
import com.haierp.model.LogisticType;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.model.sale.OuterOrder;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IOuterOrderService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.IShippingOrderService;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.MapUtil;
import com.haierp.util.Money;
import com.haierp.util.NumberUtil;
import com.haierp.vo.ShippingOrderQueryVO;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

@Service("shippingOrderService")
public class ShippingOrderServiceImpl extends SuperServiceImpl<ShippingOrderMapper, ShippingOrder> implements IShippingOrderService {

	@Autowired
	private ShippingOrderMapper shippingOrderMapper;
	
	@Autowired
	private IErpOrderService erpOrderService;
	
	@Autowired
	private IInventoryService inventoryService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	
	@Autowired
	private ErpOrderMapper erpOrderMapper;
	
	@Autowired
	private LogisticCompanyMapper logisticCompanyMapper;
	
	@Autowired
	private IOuterOrderService outerOrderService;
	
	
	@Autowired
	private ShippingTrackMapper shippingTrackMapper;
	
	@Autowired
	private LogisticTypeMapper logisticTypeMapper;
	
	@Override
	public JsonPageResult<List<ShippingOrder>> queryShippingOrders(ShippingOrderQueryVO shippingOrderQueryVO) {
		JsonPageResult<List<ShippingOrder>> shippingOrderResult = new JsonPageResult<>();
		// 1、查询总的记录数量
		Integer totalCount = shippingOrderMapper.queryShippingOrdersCount(shippingOrderQueryVO);
		// 2、查询分页记录
		if (totalCount != null && totalCount != 0L) {
			shippingOrderResult.buildPage(totalCount, shippingOrderQueryVO);
			List<ShippingOrder> shippingOrders = shippingOrderMapper.queryShippingOrders(shippingOrderQueryVO);
			boolean checkFlag = false;
			for (ShippingOrder shippingOrder : shippingOrders) {
				List<ShippingTrack> shippingTracks = shippingTrackMapper
						.queryShippingTrack(shippingOrder.getShippingNo());
				if (shippingTracks.size() == 0) {
					Date date = shippingOrder.getGmtCreate();
					Date dateNow = new Date();
					int days = (int) ((dateNow.getTime() - date.getTime()) / (1000 * 3600 * 24));
					if (days >= 7) {
						checkFlag = true;
					}
				}
				if (CollectionUtils.isNotEmpty(shippingTracks)) {
					if (shippingTracks.size() == 1) {
						Date date = shippingTracks.get(0).getGmtCreate();
						Date dateNow = new Date();
						int days = (int) ((dateNow.getTime() - date.getTime()) / (1000 * 3600 * 24));
						if (days >= 7) {
							checkFlag = true;
						}
					} else {
						for (int i = shippingTracks.size() - 1; i >= 0; i--) {
							Date dateOne = shippingTracks.get(i).getGmtCreate();
							Date dateTwo = shippingTracks.get(i - 1 + 1).getGmtCreate();
							int days = (int) ((dateOne.getTime() - dateTwo.getTime()) / (1000 * 3600 * 24));
							if (days >= 7) {
								checkFlag = true;
							}
						}
					}
				}
				shippingOrder.setIsSlowly(checkFlag);
			}
			shippingOrderResult.setData(shippingOrders);
		} else {
			List<ShippingOrder> shippingOrders = new ArrayList<>();
			shippingOrderResult.setData(shippingOrders);
		}
		return shippingOrderResult;
	}

	@Override
	public Set<Long> multiDelivery(ShippingOrder shippingOrder,Long companyId) throws InventoryException {
		String erpOrderIds = shippingOrder.getErpOrderId();
		StringBuffer erpNos = new StringBuffer();
		String s = erpOrderIds.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ErpOrder>  erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
		for (ErpOrder erpOrder : erpOrderList) {
			OuterOrder orderone = outerOrderService.selectById(erpOrder.getOuterOrderId());
			if( orderone.getStatus() == null || orderone.getStatus() == -3) {
				throw new ErpCommonException("主订单未付款，主订单号：" + orderone.getOrderNo());
			}
		}
		double skuWeight = 0.0D;
		for(ErpOrder erpOrder : erpOrderList) {
			if((erpOrder.getStockStatus()==StockUpStatus.STOCKUP.getCode() || erpOrder.getStockStatus()==StockUpStatus.PREPARE.getCode()) && erpOrder.getShippingOrderId()==null) {
				//拼接erp_no
				if(erpNos.length() < 1) {
					erpNos.append(erpOrder.getErpNo());
				} else {
					erpNos.append("," + erpOrder.getErpNo());
				}
				//扣减库存
				inventoryService.sendInventroyOrder(erpOrder);
				//修改子订单状态
				erpOrder.setStatus(OrderStatus.SENT.getCode());
			} else if(erpOrder.getStockStatus()!=StockUpStatus.STOCKUP.getCode()) {
				throw new ErpCommonException("商品备货状态不对，子订单号：" + erpOrder.getErpNo());
			} else {
				throw new ErpCommonException("商品不能重复发货，子订单号：" + erpOrder.getErpNo());
			}
			if(erpOrder.getWeight() != null) {
				skuWeight += erpOrder.getWeight()*erpOrder.getQuantity();
			}
		}
		if(skuWeight > 0) {
			if (shippingOrder.getShippingType() == 1 && shippingOrder.getLogisticCompany().equals("4PX")) {
				shippingOrder.setSkuWeight(shippingOrder.getWeightOut());	//仓库预估
			} else {
				shippingOrder.setSkuWeight(skuWeight);	//包裹里面的sku的重量(磅)
			}
			double totalWeight = 0D;
			if(shippingOrder.getSkuWeight()+0.33 < 1) {	//不足1磅的按1磅计
				totalWeight = 1;
			} else {
				totalWeight = Math.ceil((shippingOrder.getSkuWeight()+0.33)*10);
				totalWeight = totalWeight/10;
			}
			if(shippingOrder.getLogisticCompany().equals("邮客")) {
				if(shippingOrder.getType() == 6 || shippingOrder.getType() == 11) {	//邮客食品线（2.2/磅）
					shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*2.2));
				} else if(shippingOrder.getType() == 7) {	//邮客奶粉线(包邮)
					shippingOrder.setFreight(0D);
				} else if(shippingOrder.getType() == 10){  //邮客经济线路 （3.0/磅）
					shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.0));
				}else {
					shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.5));//邮客包税线
				}
			} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==4) {
				shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.7));
			} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==5) {
				shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*4.2));
			}
		}
		if(shippingOrder.getStatus() == null) {
			shippingOrder.setStatus(ShippingOrderStatus.INIT.getCode());
		}
		shippingOrder.setErpNo(erpNos.toString());
		if(companyId==2){
			shippingOrder.setShippingNo("YB"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//艺博发货单号
		} else if (companyId==1 && shippingOrder.getLogisticCompany().equals("海带宝")) {
			shippingOrder.setShippingNo("HDBPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//海带宝发货单号
		} else if(companyId==1 && shippingOrder.getLogisticCompany().equals("4PX") && erpOrderList.get(0).getWarehouseId() == 4) {
			shippingOrder.setShippingNo("4PXLAX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花LA发货
		} else if(companyId==1 && shippingOrder.getLogisticCompany().equals("4PX") && erpOrderList.get(0).getWarehouseId() == 1) {
			shippingOrder.setShippingNo("4PXPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花Por发货
		} else if(companyId==1 && shippingOrder.getLogisticCompany().equals("邮客")) {
			shippingOrder.setShippingNo("YKPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花邮客发货
		} else if(companyId==1 && shippingOrder.getLogisticCompany().equals("运通快递")) {
			shippingOrder.setShippingNo("YTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
		} else if(companyId==1 && shippingOrder.getLogisticCompany().equals("海淘一号仓")) {
			shippingOrder.setShippingNo("HTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
		} else if(companyId==3) {
			shippingOrder.setShippingNo("RY"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//如花箱包店单号生产规则
		} else {
			shippingOrder.setShippingNo("RH"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//如花发货
		}

		shippingOrder.setGmtCreate(new Date());
		shippingOrder.setGmtModify(new Date());
		shippingOrder.setIsPay(0);//默认未支付账单
		this.insert(shippingOrder);
		
		Set<Long> mainIds = Sets.newHashSet();
		for(ErpOrder erpOrder : erpOrderList) {
			erpOrder.setShippingOrderId(shippingOrder.getId());
			erpOrder.setShippingNo(shippingOrder.getShippingNo());
			erpOrder.setLogisticType(shippingOrder.getShippingType());
			mainIds.add(erpOrder.getOuterOrderId());
		}
		erpOrderService.updateBatchById(erpOrderList);
		return mainIds;
	}
	
	@Override
	public Map<String, Set<Long>> batchDelivery(ShippingOrder shippingOrder) throws InventoryException {
		String erpOrderIds = shippingOrder.getErpOrderId();
		String s = erpOrderIds.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		/*if(shippingOrder.getIsBatch()==0 && erpOrderIdList.size()>1) {
			throw new ErpCommonException("此操作仅为一个子订单发货，而您选中了多个子订单！");
		}*/
		
		if(shippingOrder.getStatus() == null) {
			shippingOrder.setStatus(ShippingOrderStatus.INIT.getCode());
		}
		Date nowDate = new Date();
		Map<String, Set<Long>> resultMap = new HashMap<>();
		Set<Long> mainIds = Sets.newHashSet();
		Set<Long> shippingOrderIds = Sets.newHashSet();
		//List<ErpOrder>  erpOrderList = erpOrderService.selectBatchIds(erpOrderIdList);
		List<ErpOrder> erpOrderList = this.queryShippingOrderDetail(shippingOrder.getErpOrderId());
		for(ErpOrder erpOrder : erpOrderList) {
			if(erpOrder.getStockStatus()==StockUpStatus.STOCKUP.getCode() && erpOrder.getShippingOrderId()==null) {
				//扣减库存
				inventoryService.sendInventroyOrder(erpOrder);
				//修改子订单状态
				erpOrder.setStatus(OrderStatus.SENT.getCode());
			} else if(erpOrder.getStockStatus()!=StockUpStatus.STOCKUP.getCode()) {
				throw new ErpCommonException("商品备货状态不对，子订单号：" + erpOrder.getErpNo());
			} else {
				throw new ErpCommonException("商品不能重复发货，子订单号：" + erpOrder.getErpNo());
			}
			if(shippingOrder.getCompanyId()== 1L && !shippingOrder.getLogisticCompany().equals("国内物流公司") && !shippingOrder.getLoginName().equals("steph") && shippingOrder.getIsAutoShipe() == 1) {
				boolean ifDoubleShoes = false;
				boolean ifCostco = false;
				List<ErpOrder> ErpOrderPrice = this.queryShippingOrderDetail("[" + erpOrder.getId() + "]");
				double priceTotall = erpOrder.getSalePrice() * erpOrder.getQuantity();
				if(erpOrder.getCategoryName().equals("鞋靴") && erpOrder.getQuantity()>1){
					ifDoubleShoes = true;
				}
				 if(!erpOrder.getBuySite().contains("Costco") && (erpOrder.getCategoryName().equals("男装") || erpOrder.getCategoryName().equals("女装") || erpOrder.getCategoryName().equals("潮流服饰"))) {
					 ifCostco = true;
				 }
				ShippingOrderQueryVO ykShipping = Money.getYeType(ErpOrderPrice);
				ShippingOrderQueryVO pxShipping = Money.getPxType(ErpOrderPrice);
				if ((ykShipping.getFinallyFreight() < pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(erpOrder.getIdCard()) && priceTotall<= 1700.00) {
					shippingOrder.setLogisticCompany("邮客");
					shippingOrder.setType(ykShipping.getBestType());
					shippingOrder.setFreight(ykShipping.getFinallyFreight());
				} else if((ykShipping.getFinallyFreight() > pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(erpOrder.getIdCard())) {
					shippingOrder.setLogisticCompany("4PX");
					shippingOrder.setType(pxShipping.getBestType());
					shippingOrder.setFreight(pxShipping.getFinallyFreight());
				} 
				if (StringUtils.isBlank(erpOrder.getIdCard())) {
					shippingOrder.setLogisticCompany("运通快递");
					shippingOrder.setType(4);
				}
				if(ErpOrderPrice.size() == 1 && ErpOrderPrice.get(0).getCategoryName().equals("潮流香水")) {
					shippingOrder.setLogisticCompany("运通快递");
					shippingOrder.setType(5);
				}
				if(shippingOrder.getLogisticCompany().equals("邮客") && shippingOrder.getType() == 10 && ifCostco){
					shippingOrder.setLogisticCompany("4PX");
					shippingOrder.setType(pxShipping.getBestType());
					shippingOrder.setFreight(pxShipping.getFinallyFreight());
				}
				//paike匹配
				if(ErpOrderPrice.size() == 1 && ErpOrderPrice.get(0).getItemCode().equals("I0301001Q66848") && StringUtils.isNotBlank(ErpOrderPrice.get(0).getIdCard())) {
					shippingOrder.setLogisticCompany("邮客");
					if(ErpOrderPrice.get(0).getQuantity() > 1) {
						shippingOrder.setType(1);
					} else {
						shippingOrder.setType(10);
					}
				}
				//核对邮客食品线
				if (shippingOrder.getLogisticCompany().equals("邮客") && shippingOrder.getType() == 6) {
					if(erpOrder.getPurchasePrice() == null || erpOrder.getPurchasePrice() <= 1.00) {
						throw new ErpCommonException("食品线采购价格有误请给采购人员核对此采购价 SKUCODE:" + erpOrder.getSkuCode());
					}
					boolean specially = false;
					Map<String, String> categorymap = MapUtil.getCategoryNoFda();
					String category = erpOrder.getCategoryName();
					for (Map.Entry<String, String> entry : categorymap.entrySet()) {
						if (category.equals(entry.getKey())) {
							specially = true;
						}
					}

					/*if (specially && !erpOrder.getItemName().contains("内裤") && !erpOrder.getItemName().contains("内衣") && !erpOrder.getItemCode().equals("I0403001Q12440")) {
						shippingOrder.setLogisticCompany("4PX");
						shippingOrder.setType(8);
						shippingOrder.setFreight(pxShipping.getFinallyFreight());
					}*/
				}
				if(StringUtils.isNotBlank(erpOrder.getIdCard())) {
					EntityWrapper<ShippingOrder> entityWrapper = new EntityWrapper<ShippingOrder>();
					entityWrapper.where("id_card={0} and logistic_company={1} and gmt_create>=DATE_SUB(CURDATE(), INTERVAL 6 DAY)", erpOrder.getIdCard(), shippingOrder.getLogisticCompany());
					int num = this.selectCount(entityWrapper);
					if(num >= 2 && shippingOrder.getLogisticCompany().equals("邮客")) {
						throw new ErpCommonException("该身份证已经在一周内发货两次,请在批量发货中剔除此子订单：" + erpOrder.getErpNo() + "收件人：" +erpOrder.getReceiver());
					} 
					if(num >= 5 && shippingOrder.getLogisticCompany().equals("4PX")) {
						throw new ErpCommonException("该身份证已经在一周内发货五次,请在批量发货中剔除此子订单：" + erpOrder.getErpNo() + "收件人：" +erpOrder.getReceiver());
					}
				}
				if(shippingOrder.getLogisticCompany() != null && shippingOrder.getLogisticCompany().equals("4PX")) {
					if (priceTotall>1000) {
						throw new ErpCommonException("此单包裹总额超过4PX上限： 订单号:" + erpOrder.getErpNo());
					}
				}
			}

			//红酒线校验
			if (shippingOrder.getLogisticCompany() != null && shippingOrder.getLogisticCompany().equals("4PX") && shippingOrder.getType() == 18) {
				if (erpOrder.getPurchasePrice() == null || erpOrder.getPurchasePrice() < 12.00 || erpOrder.getPurchasePrice() > 20.00) {
					throw new ErpCommonException("红酒线该商品采购价格异常,请核对后发货： SKUCODE:" + erpOrder.getSkuCode());
				}
				if(erpOrder.getQuantity() > 6) {
					throw new ErpCommonException("超出红酒线的上限数量6个,请调整此订单发货" + erpOrder.getErpNo());
				}
			}
			shippingOrder.setErpOrderId("[" + erpOrder.getId() + "]");
			shippingOrder.setReceiver(erpOrder.getReceiver());
			shippingOrder.setReceiverState(erpOrder.getReceiverState());
			shippingOrder.setReceiverCity(erpOrder.getReceiverCity());
			shippingOrder.setReceiverDistrict(erpOrder.getReceiverDistrict());
			shippingOrder.setIdCard(erpOrder.getIdCard());
			shippingOrder.setTelephone(erpOrder.getTelephone());
			shippingOrder.setPostcode(erpOrder.getPostcode());
			shippingOrder.setRemark(erpOrder.getRemark());
			shippingOrder.setAddressDetail(erpOrder.getAddressDetail());
			shippingOrder.setErpNo(erpOrder.getErpNo());
			shippingOrder.setIsPay(0);//默认未支付
			if(erpOrder.getCompanyId()==2) {
				shippingOrder.setShippingNo("YB"+DateUtil.formatDate(nowDate, DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//艺博发货单号
			} else if (erpOrder.getCompanyId()==1 && shippingOrder.getLogisticCompany().equals("海带宝")) {
				shippingOrder.setShippingNo("HDBPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//海带宝发货单号
			} else if (erpOrder.getCompanyId()==1 && erpOrder.getWarehouseId() == 4 && shippingOrder.getLogisticCompany().equals("4PX")) {
				shippingOrder.setShippingNo("4PXLAX"+DateUtil.formatDate(nowDate, DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花LA发货单号
			} else if (erpOrder.getCompanyId()==1 && erpOrder.getWarehouseId() == 1 && shippingOrder.getLogisticCompany().equals("4PX")) {
				shippingOrder.setShippingNo("4PXPDX"+DateUtil.formatDate(nowDate, DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花Por发货单号
			} else if (erpOrder.getCompanyId()==1 && shippingOrder.getLogisticCompany().equals("邮客")) {
				shippingOrder.setShippingNo("YKPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());//如花邮客发货
			} else if (erpOrder.getCompanyId()==1 && shippingOrder.getLogisticCompany().equals("运通快递")) {
				shippingOrder.setShippingNo("YTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			} else if (erpOrder.getCompanyId()==1 && shippingOrder.getLogisticCompany().equals("海淘一号仓")) {
				shippingOrder.setShippingNo("HTPDX"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+sequenceUtilService.gainPKGSequence());
			} else if (erpOrder.getCompanyId()==3) {
				shippingOrder.setShippingNo("RY"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//如花箱包店单号生产规则
			} else {
				shippingOrder.setShippingNo("RH"+DateUtil.formatDate(nowDate, DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//如花发货单号
			}
			if(erpOrder.getWeight() != null) {
				double skuWeight = erpOrder.getWeight()*erpOrder.getQuantity();
				if (shippingOrder.getShippingType()!= null && shippingOrder.getShippingType() == 1) {
					shippingOrder.setSkuWeight(shippingOrder.getWeightOut());	//仓库预估
				} else {
					shippingOrder.setSkuWeight(skuWeight);	//包裹里面的sku的重量(磅)
				}
				double totalWeight = 0D;
				if(shippingOrder.getSkuWeight()+0.33 < 1) {	//不足1磅的按1磅计
					totalWeight = 1;
				} else {
					totalWeight = Math.ceil((shippingOrder.getSkuWeight()+0.33)*10);
					totalWeight = totalWeight/10;
				}
				
				if(shippingOrder.getLogisticCompany().equals("邮客")) {
					if(shippingOrder.getType() == 6 || shippingOrder.getType() == 11) {	//如花和艺博的食品线（2.2/磅）
						shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*2.2));
					} else if(shippingOrder.getType() == 7) {	//邮客奶粉线(包邮)
						shippingOrder.setFreight(0D);
					} else if(shippingOrder.getType() == 10){  //邮客经济线路 （3.0/磅）
						shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.0));
					}else {
						shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.5));//邮客包税线
					}
				} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==4) {
					shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.7));
				} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==5) {
					shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*4.2));
				}
			}
			shippingOrder.setGmtCreate(nowDate);
			shippingOrder.setGmtModify(nowDate);
			this.insert(shippingOrder);
			
			//对接邮客、运通快递
			if(shippingOrder.getLogisticCompany()!=null && (shippingOrder.getLogisticCompany().equals("邮客") || shippingOrder.getLogisticCompany().equals("运通快递") || shippingOrder.getLogisticCompany().equals("4PX") || shippingOrder.getLogisticCompany().equals("联邦转运") || shippingOrder.getLogisticCompany().equals("海带宝"))) {
				shippingOrderIds.add(shippingOrder.getId());
			}
			
			erpOrder.setShippingOrderId(shippingOrder.getId());
			erpOrder.setShippingNo(shippingOrder.getShippingNo());
			mainIds.add(erpOrder.getOuterOrderId());
		}
		
		erpOrderService.updateBatchById(erpOrderList);
		
		resultMap.put("mainIds", mainIds);
		resultMap.put("shippingOrderIds", shippingOrderIds);
		return resultMap;
	}
	
	@Override
	public MultiDeliveryFormDTO queryByErpOrderId(String erpOrderId) {
		MultiDeliveryFormDTO multiDeliveryFormDTO = new MultiDeliveryFormDTO();
		
		String s = erpOrderId.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ErpOrder> ErpOrderList = erpOrderMapper.queryByErpOrderId(erpOrderIdList);
		List<ErpOrder> totalErpOrderList = new ArrayList<ErpOrder>();
		
		String receiver=null;
		String telephone=null;
		String addressDetail=null;
		Set<Long> erpOrderIdSet = Sets.newHashSet();
		
		Double skuWeight = 0D;
		Double totalSalePrice = 0D;
		for(ErpOrder erpOrder : ErpOrderList) {
			if(erpOrder.getStockStatus()==null || (erpOrder.getStockStatus()!=StockUpStatus.STOCKUP.getCode() && erpOrder.getStockStatus()!=StockUpStatus.PREPARE.getCode())) {
				throw new ErpCommonException("商品备货状态不对，子订单号：" + erpOrder.getErpNo());
			}
			if(StringUtils.isBlank(erpOrder.getReceiver()) || StringUtils.isBlank(erpOrder.getTelephone()) || StringUtils.isBlank(erpOrder.getReceiverState()) || StringUtils.isBlank(erpOrder.getReceiverCity()) || StringUtils.isBlank(erpOrder.getReceiverDistrict())) {
				throw new ErpCommonException("收货人地址不能为空：" + erpOrder.getErpNo());
			}
			if(erpOrder.getWeight()!=null) {
				skuWeight += erpOrder.getWeight()*erpOrder.getQuantity();
			}
			totalSalePrice += erpOrder.getSalePrice()*erpOrder.getQuantity();
			if(StringUtils.isBlank(receiver)) {
				receiver = erpOrder.getReceiver();
				telephone = erpOrder.getTelephone();
				addressDetail = erpOrder.getAddressDetail();
				
				multiDeliveryFormDTO.setReceiver(erpOrder.getReceiver());
				multiDeliveryFormDTO.setReceiverState(erpOrder.getReceiverState());
				multiDeliveryFormDTO.setReceiverCity(erpOrder.getReceiverCity());
				multiDeliveryFormDTO.setReceiverDistrict(erpOrder.getReceiverDistrict());
				multiDeliveryFormDTO.setIdCard(erpOrder.getIdCard());
				multiDeliveryFormDTO.setTelephone(erpOrder.getTelephone());
				multiDeliveryFormDTO.setPostcode(erpOrder.getPostcode());
				multiDeliveryFormDTO.setRemark(erpOrder.getRemark());
				multiDeliveryFormDTO.setAddressDetail(erpOrder.getAddressDetail());
			} else if (StringUtils.isBlank(multiDeliveryFormDTO.getIdCard())){
				multiDeliveryFormDTO.setInfo("子订单身份证号为空，请注意核对！");
			}
			else if(!receiver.equals(erpOrder.getReceiver()) || !telephone.equals(erpOrder.getTelephone()) || !addressDetail.equals(erpOrder.getAddressDetail())) {
				multiDeliveryFormDTO.setInfo("子订单收货信息不一致，请注意核对！");
			}
			if(erpOrderIdSet.contains(erpOrder.getId())) {
				continue;
			}
			
			//搜索同一收货人的子订单
			ErpOrder tjErpOrder = new ErpOrder();
			tjErpOrder.setReceiver(erpOrder.getReceiver());
			tjErpOrder.setTelephone(erpOrder.getTelephone());
			tjErpOrder.setReceiverState(erpOrder.getReceiverState());
			tjErpOrder.setReceiverCity(erpOrder.getReceiverCity());
			tjErpOrder.setReceiverDistrict(erpOrder.getReceiverDistrict());
			tjErpOrder.setStatus(0);								//订单状态：新建
			//tjErpOrder.setStockStatus(erpOrder.getStockStatus());	//备货状态：已备货
			//tjErpOrder.setWarehouseId(erpOrder.getWarehouseId());	//相同仓库
			EntityWrapper<ErpOrder>  entityWrapper = new EntityWrapper<ErpOrder>();
			entityWrapper.setEntity(tjErpOrder);
			List<ErpOrder> selErpOrderList = erpOrderService.selectList(entityWrapper);
			for(int i=0; i<selErpOrderList.size(); i++) {
				ErpOrder selErpOrder= selErpOrderList.get(i);
				//不在同一仓库的情况，不用考虑
				if(selErpOrder.getWarehouseId()!=null && selErpOrder.getWarehouseId()!=erpOrder.getWarehouseId()) continue;
				//在同一仓库的或者未备货的
				if(!erpOrderIdSet.contains(selErpOrder.getId())) {
					String positionNoStr = erpOrderMapper.selectPositionNoByErpOrderId(selErpOrder.getId());
					selErpOrder.setPositionNo(positionNoStr);
					totalErpOrderList.add(selErpOrder);
					erpOrderIdSet.add(selErpOrder.getId());
				}
			}
		}
		Collections.sort(totalErpOrderList, new Comparator<ErpOrder>() {
            @Override
            public int compare(ErpOrder o1, ErpOrder o2) {
                 return o2.getStockStatus().compareTo(o1.getStockStatus()); 
            }  
 
        });
		multiDeliveryFormDTO.setSkuWeight(skuWeight);
		multiDeliveryFormDTO.setTotalSalePrice(totalSalePrice);
		multiDeliveryFormDTO.setErpOrderList(totalErpOrderList);
		return multiDeliveryFormDTO;
	}
	
	@Override
	public List<ErpOrder> queryShippingOrderDetail(String erpOrderIds) {
		if(StringUtil.isBlank(erpOrderIds)) {
			throw new ErpCommonException("子订单号为空");
		}
		String s = erpOrderIds.replace("&quot;", "\"");
		List<Long> erpOrderIdList = HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		List<ErpOrder> ErpOrderList = erpOrderMapper.queryByErpOrderId(erpOrderIdList);
		ErpOrderList.forEach(erpOrder ->{
			//在同一仓库的或者未备货的
			String positionNoStr = erpOrderMapper.selectPositionNoByErpOrderId(erpOrder.getId());
			erpOrder.setPositionNo(positionNoStr);
		});
		return ErpOrderList;
	}
	
	@Override
	public void update(ShippingOrder shippingOrder) {
		//修改发货单
		shippingOrder.setUserModify(shippingOrder.getUserCreate());
		shippingOrder.setUserCreate(null);
		shippingOrder.setGmtModify(new Date());
		shippingOrderMapper.updateSelectiveById(shippingOrder);
	}
	
	@Override
	public List<LogisticCompany> queryLogisticCompany() {
		List<LogisticCompany> LogisticCompany = logisticCompanyMapper.selectList(new EntityWrapper<LogisticCompany>());
		return LogisticCompany;
	}
	
	@Override
	public List<ErpOrder> queryByShippingOrderTime(ShippingOrderQueryVO shippingOrderQueryVO) {
		List<ErpOrder> ErpOrderList = erpOrderMapper.queryByShippingOrderTime(shippingOrderQueryVO);
		return ErpOrderList;
	}
	
	@Override
	public List<ShippingOrder> queryByShippingOrderPackageTime(ShippingOrderQueryVO shippingOrderQueryVO) {
		List<ShippingOrder> shippingOrderList = this.baseMapper.queryByShippingOrderPackageTime(shippingOrderQueryVO);
		return shippingOrderList;
	}
	/**
	 * 更新主订单状态
	 * @param mainIds
	 */
	@Override
	public void updateOuterstatus(Set<Long> mainIds) {
		for(Long mainId:mainIds){
			if (mainId != null) {
				OuterOrder outerOrder = outerOrderService.selectById(mainId);
				if (outerOrder != null) {
					EntityWrapper<ErpOrder> entityWrapper = new EntityWrapper<>();
					//entityWrapper.where("outer_order_id={0} and status=0", mainId);
					//int count = erpOrderService.selectCount(entityWrapper);
					entityWrapper.where("outer_order_id={0}", mainId);
					List<ErpOrder> erpOrderList = erpOrderService.selectList(entityWrapper);
					int totalCount = erpOrderList.size();
					int initCount = 0;
					int sentCount = 0;
					int closeCount = 0;
					if(totalCount > 0) {
						for(int i=0; i<totalCount; i++) {
							switch(erpOrderList.get(i).getStatus()) {
								case 0:
									initCount++;
									break;
								case 2:
									sentCount++;
									break;
								case -1:
									closeCount++;
									break;
							}
						}
					}
					if(closeCount == totalCount) {	//主订单关闭
						outerOrder.setStatus(OrderStatus.CLOSE.getCode());
					} else if((closeCount+sentCount) == totalCount) {	//全部发货
						outerOrder.setStatus(OrderStatus.SENT.getCode());
					} else if(sentCount > 0) {	//部分发货
						outerOrder.setStatus(OrderStatus.PART_SENT.getCode());
					} else {
						outerOrder.setStatus(OrderStatus.INIT.getCode());
					}
					outerOrder.setGmtModify(new Date());
					outerOrderService.updateById(outerOrder);
				}
			}
		}
	}

	@Override
	public void updateStatusByShippingNo(String shippingNo) {
		shippingOrderMapper.updateStatusByShippingNo(shippingNo);
		
	}

	@Override
	public List<ShippingOrder> queryAllInHaihu() {
		EntityWrapper<ShippingOrder> selEntityWrapper = new EntityWrapper<ShippingOrder>();
		selEntityWrapper.where("logistic_company={0} and status<> 2", "海狐");
		List<ShippingOrder> haihuOrders = this.selectList(selEntityWrapper);
		return haihuOrders;
	}

	@Override
	public List<ShippingOrder> queryAllFourPx() {
		EntityWrapper<ShippingOrder> selEntityWrapper = new EntityWrapper<ShippingOrder>();
		selEntityWrapper.where("logistic_company={0} and status<> 2 and company_id <> 2", "4PX");
		selEntityWrapper.orderBy("id desc");
		List<ShippingOrder> shippingOrders = this.selectList(selEntityWrapper);
		return shippingOrders;
	}

	@Override
	public List<ShippingOrder> queryAllFourPxTwo() {
		EntityWrapper<ShippingOrder> selEntityWrapper = new EntityWrapper<ShippingOrder>();
		selEntityWrapper.where("logistic_company={0} and status<> 2 and gmt_create < DATE_SUB(NOW(), INTERVAL 4 DAY)", "4PX");
		List<ShippingOrder> shippingOrders = this.selectList(selEntityWrapper);
		return shippingOrders;
	}

	@Override
	public List<ShippingOrder> queryAllFad() {
		EntityWrapper<ShippingOrder> selEntityWrapper = new EntityWrapper<ShippingOrder>();
		selEntityWrapper.where("logistic_company={0} and status<> 2", "联邦转运");
		selEntityWrapper.orderBy("id desc");
		List<ShippingOrder> shippingOrders = this.selectList(selEntityWrapper);
		return shippingOrders;
	}

	@Override
	public List<LogisticType> queryLogisticType() {
		List<LogisticType> LogisticType = logisticTypeMapper.selectList(new EntityWrapper<LogisticType>());
		return LogisticType;
	}

/*	@Override
	public void shippingAuto() throws InventoryException {
		ShippingOrder shippingOrder = new ShippingOrder();
		shippingOrder.setCompanyId(1L);
		shippingOrder.setUserCreate("定时发货");
		List<ErpOrder> ErpOrderList = erpOrderMapper.queryShippingRightNow();
		Map<String, Set<Long>> resultMap = new HashMap<>();
		Set<Long> mainIds = Sets.newHashSet();
		Set<Long> shippingOrderIds = Sets.newHashSet();
		if(ErpOrderList.size()>0) {
			for(ErpOrder erpOrder : ErpOrderList) {
				if(erpOrder.getStockStatus()==StockUpStatus.STOCKUP.getCode() && erpOrder.getShippingOrderId()==null) {
					//扣减库存
					inventoryService.sendInventroyOrder(erpOrder);
					//修改子订单状态
					erpOrder.setStatus(OrderStatus.SENT.getCode());
				} else if(erpOrder.getStockStatus()!=StockUpStatus.STOCKUP.getCode()) {
					throw new ErpCommonException("商品备货状态不对，子订单号：" + erpOrder.getErpNo());
				} else {
					throw new ErpCommonException("商品不能重复发货，子订单号：" + erpOrder.getErpNo());
				}
				//if(shippingOrder.getCompanyId()== 1L && !shippingOrder.getLogisticCompany().equals("国内物流公司") && !shippingOrder.getLoginName().equals("steph")) {
					boolean ifDoubleShoes = false;
					List<ErpOrder> ErpOrderPrice = this.queryShippingOrderDetail("[" + erpOrder.getId() + "]");
					double priceTotall = erpOrder.getSalePrice() * erpOrder.getQuantity();
					if(erpOrder.getCategoryName().equals("鞋靴") && erpOrder.getQuantity()>1){
						ifDoubleShoes = true;
					}
					ShippingOrderQueryVO ykShipping = Money.getYeType(ErpOrderPrice);
					ShippingOrderQueryVO pxShipping = Money.getPxType(ErpOrderPrice);
					if ((ykShipping.getFinallyFreight() < pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(erpOrder.getIdCard()) && priceTotall<= 1700.00) {
						shippingOrder.setLogisticCompany("邮客");
						shippingOrder.setType(ykShipping.getBestType());
					} else if((ykShipping.getFinallyFreight() > pxShipping.getFinallyFreight()) && StringUtils.isNotBlank(erpOrder.getIdCard()) && !ifDoubleShoes && priceTotall<= 1000){
						shippingOrder.setLogisticCompany("4PX");
						shippingOrder.setType(9);
					} else {
						shippingOrder.setLogisticCompany("4PX");
						shippingOrder.setType(8);
					}
				//}
				shippingOrder.setErpOrderId("[" + erpOrder.getId() + "]");
				shippingOrder.setReceiver(erpOrder.getReceiver());
				shippingOrder.setReceiverState(erpOrder.getReceiverState());
				shippingOrder.setReceiverCity(erpOrder.getReceiverCity());
				shippingOrder.setReceiverDistrict(erpOrder.getReceiverDistrict());
				shippingOrder.setIdCard(erpOrder.getIdCard());
				shippingOrder.setTelephone(erpOrder.getTelephone());
				shippingOrder.setPostcode(erpOrder.getPostcode());
				shippingOrder.setRemark(erpOrder.getRemark());
				shippingOrder.setAddressDetail(erpOrder.getAddressDetail());
				shippingOrder.setErpNo(erpOrder.getErpNo());
				shippingOrder.setIsPay(0);//默认未支付
				if(erpOrder.getCompanyId()==2){
					shippingOrder.setShippingNo("LYB"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//艺博发货单号
				}else if (erpOrder.getCompanyId()==1 && shippingOrder.getLogisticCompany().equals("海带宝")) {
					shippingOrder.setShippingNo("HDB"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//海带宝发货单号
				}else{
					shippingOrder.setShippingNo("PKG"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDDHHMMSS)+sequenceUtilService.gainPKGSequence());//如花发货单号
				}
				if(erpOrder.getWeight() != null) {
					double skuWeight = erpOrder.getWeight()*erpOrder.getQuantity();
					if (shippingOrder.getShippingType()!= null && shippingOrder.getShippingType() == 1) {
						shippingOrder.setSkuWeight(shippingOrder.getWeightOut());	//仓库预估
					} else {
						shippingOrder.setSkuWeight(skuWeight);	//包裹里面的sku的重量(磅)
					}
					double totalWeight = 0D;
					if(shippingOrder.getSkuWeight()+0.33 < 1) {	//不足1磅的按1磅计
						totalWeight = 1;
					} else {
						totalWeight = Math.ceil((shippingOrder.getSkuWeight()+0.33)*10);
						totalWeight = totalWeight/10;
					}
					
					if(shippingOrder.getLogisticCompany().equals("邮客")) {
						if(shippingOrder.getType() == 6 || shippingOrder.getType() == 11) {	//如花和艺博的食品线（2.2/磅）
							shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*2.2));
						} else if(shippingOrder.getType() == 7) {	//邮客奶粉线(包邮)
							shippingOrder.setFreight(0D);
						} else if(shippingOrder.getType() == 10){  //邮客经济线路 （3.0/磅）
							shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.0));
						}else {
							shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.5));//邮客包税线
						}
					} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==4) {
						shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*3.7));
					} else if(shippingOrder.getLogisticCompany().equals("运通快递") && shippingOrder.getType()==5) {
						shippingOrder.setFreight(NumberUtil.formatDouble2(totalWeight*4.2));
					}
				}
				shippingOrder.setGmtCreate(new Date());
				shippingOrder.setGmtModify(new Date());
				this.insert(shippingOrder);
				
				//对接邮客、运通快递
				if(shippingOrder.getLogisticCompany()!=null && (shippingOrder.getLogisticCompany().equals("邮客") || shippingOrder.getLogisticCompany().equals("运通快递") || shippingOrder.getLogisticCompany().equals("4PX") || shippingOrder.getLogisticCompany().equals("联邦转运") || shippingOrder.getLogisticCompany().equals("海带宝"))) {
					shippingOrderIds.add(shippingOrder.getId());
				}
				
				erpOrder.setShippingOrderId(shippingOrder.getId());
				erpOrder.setShippingNo(shippingOrder.getShippingNo());
				mainIds.add(erpOrder.getOuterOrderId());
			}
		}
		erpOrderService.updateBatchById(ErpOrderList);
		resultMap.put("mainIds", mainIds);
		resultMap.put("shippingOrderIds", shippingOrderIds);
		Set<Long> mainIdss = resultMap.get("mainIds");
		//更新主订单发货状态
		if(CollectionUtils.isNotEmpty(mainIdss)){
			this.updateOuterstatus(mainIds);
		}
		Set<Long> shippingOrderIdss = resultMap.get("shippingOrderIds");
		//对接邮客
		if(CollectionUtils.isNotEmpty(shippingOrderIdss) && shippingOrder.getLogisticCompany().equals("邮客")) {
			for(Long shippingOrderId : shippingOrderIdss) {
				youkeService.createOrder(shippingOrderId);
			}
		}
		//对接4PX
		if(CollectionUtils.isNotEmpty(shippingOrderIdss) && shippingOrder.getLogisticCompany().equals("4PX")) {
			for (Long shippingOrderId : shippingOrderIdss) {
				siFangService.createOrder(shippingOrderId,shippingOrder.getCompanyId());
			}
		}
	}*/

}
